package fr.generali.accueilclient.gwt.client.state.store;

import java.util.ArrayList;
import java.util.Date;

import com.google.gwt.core.client.Callback;
import com.google.gwt.user.client.Cookies;

import fr.generali.accueilclient.gwt.client.state.StateStore;

/**
 * Une implémentation de {@link StateStore} qui utilise les Cookies comme moyen de persistance.
 */
public class CookieStateStore implements StateStore {

	private Date expires;
	
	private String path;
	
	private String domain;
	
	private boolean secure;
	
	private ArrayList<String> cookiesList = new ArrayList<String>();

	/** 
	 * Pour les paramètres voir {@link Cookies#setCookie(String, String, Date, String, String, boolean)}
	 * 
	 */
	public CookieStateStore(String path, Date expires, String domain, boolean secure) {
		this.path = path == null ? "/" : path;
		this.secure = secure;
		this.domain = domain;
		if (expires == null) {
			expires = new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 7)); // 7- jours
		}
		this.expires = expires;
	}

	@Override
	public void clear(String name) {
		Cookies.removeCookie(name);
	}

	@Override
	public void get(String name, Callback<String, Throwable> callback) {
		callback.onSuccess(Cookies.getCookie(name));
	}

	@Override
	public void set(String name, String value) {
		Cookies.setCookie(name, value, expires, domain, path, secure);
		
		cookiesList.add(name);
	}

	@Override
	public void clear() {
		for(String name : cookiesList){
			Cookies.removeCookie(name);	
		}
	}
}
